package com.fast.ThreadPoolFactory;

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.concurrent.*;

/**
 * CompletableFuture
 * 主要是用于串行化执行
 * thenRun    无法获取A的返回结果，无返回值
 * thenAccept 可以获取A的返回结果，无返回值
 * thenApply  可以获取A的返回结果，有返回值
 *
 * @author hjw
 * @since 2022年07月17日 17:44:00
 */
public class CF3_thenRun_thenAccept_thenApply {
    public static ThreadPoolExecutor threadPoolExecutor =  new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors() * 2,
            Runtime.getRuntime().availableProcessors() * 2,
            10,
            TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(300),
            new NamedThreadFactory("core_thread_pool_",true),
            new ThreadPoolExecutor.AbortPolicy()
    );

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("主线程开始了-----------");
        //1.AB串行化：A执行完直接执行B，不要A的执行结果,无返回值
        CompletableFuture<Void> future1 = CompletableFuture.runAsync(() -> {
            System.out.println("thenRun线程" + Thread.currentThread().getName() + "--------把任务A执行完了");
        }, threadPoolExecutor).thenRun(()->{
            System.out.println("thenRun线程"+Thread.currentThread().getName()+"把任务B执行完了");
        });

        //2.AB串行化：A执行完直接执行B，需要A的执行结果,无返回值
        CompletableFuture<Void> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("thenAccept线程" + Thread.currentThread().getName() + "--------把任务A执行完了");
            return 10;
            }, threadPoolExecutor).thenAccept((result)->{
            System.out.println("thenAccept线程"+Thread.currentThread().getName()+"把任务B执行完了"+"A的执行结果"+result);
        });
        System.out.println("主线程结束了--------------");
    }
}
